using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace CustomControls
{
    [System.ComponentModel.DesignerCategory(@"Code")]
    public class DragColorButton : Button
    {

        Point _mouseDown;

        public new string Text
        {
            get
            {
                return "";
            }
        }

        public DragColorButton()
        {
            // ReSharper disable DoNotCallOverridableMethodsInConstructor
            AllowDrop = true;
            BackColor = Color.White;
            DoubleBuffered = true;
            FlatStyle = FlatStyle.Flat;
            UseVisualStyleBackColor = false;
            base.Text = Name;
            // ReSharper restore DoNotCallOverridableMethodsInConstructor
        }

        protected override void OnMouseDown(MouseEventArgs argMevent)
        {
            //Record location of MouseDown
            _mouseDown = argMevent.Location;
            base.OnMouseDown(argMevent);
        }

        protected override void OnMouseMove(MouseEventArgs argMevent)
        {
            //If the mouse is moving and the left button is being held down...
            if (argMevent.Button == MouseButtons.Left)
            {
                //Check if the mouse has moved outside of the DragSize rectangle
                if ((Math.Abs(argMevent.Location.X - _mouseDown.X) >= SystemInformation.DragSize.Width) || (Math.Abs(argMevent.Location.Y - _mouseDown.Y) >= SystemInformation.DragSize.Height))
                {
                    DataObject tempDataObject = new DataObject(BackColor);
                    DoDragDrop(tempDataObject, DragDropEffects.Copy);
                }
            }
            base.OnMouseMove(argMevent);
        }

        protected override void OnDragEnter(DragEventArgs argDrgEvent)
        {
            List<string> itemFormats = new List<string>(argDrgEvent.Data.GetFormats());
            argDrgEvent.Effect = itemFormats.Contains("System.Drawing.Color") ? DragDropEffects.Copy : DragDropEffects.None;

            base.OnDragEnter(argDrgEvent);
        }

        protected override void OnDragDrop(DragEventArgs argDrgEvent)
        {
            List<string> itemFormats = new List<string>(argDrgEvent.Data.GetFormats());
            if (itemFormats.Contains("System.Drawing.Color"))
            {
                BackColor = (Color)argDrgEvent.Data.GetData(typeof(Color));
            }

            base.OnDragDrop(argDrgEvent);
        }
    }
}
